package com.bank.ui.customer;

import com.bank.dao.CardDAO;
import com.bank.util.UIUtils;
import com.bank.util.ValidationUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.sql.SQLException;

public class RegisterCardPanel extends JPanel {
    private final CardDAO cardDAO;
    private final String customerId;
    private final String userPID;
    private JPasswordField passwordField;
    private JTextField pidField;
    private JComboBox<String> depositTypeCombo;
    private JComboBox<String> curIDCombo;
    private JTextField openMoneyField;
    private JLabel messageLabel;
    private JLabel openDateLabel;

    public RegisterCardPanel(CardDAO cardDAO, String customerId, String userPID) {
        this.cardDAO = cardDAO;
        this.customerId = customerId;
        this.userPID = userPID;
        initializeUI();
    }

    private void initializeUI() {
        setLayout(new BorderLayout());
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 标题面板
        JPanel headerPanel = new JPanel();
        headerPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 20, 0));
        JLabel titleLabel = new JLabel("银行卡注册");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        headerPanel.add(titleLabel);
        add(headerPanel, BorderLayout.NORTH);

        // 表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("银行卡信息"),
                BorderFactory.createEmptyBorder(15, 15, 15, 15)
        ));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 密码输入框
        gbc.gridx = 0;
        gbc.gridy = 0;
        formPanel.add(new JLabel("密码 (6位数字):"), gbc);
        passwordField = new JPasswordField(20);
        passwordField.setPreferredSize(new Dimension(250, 30));
        gbc.gridx = 1;
        formPanel.add(passwordField, gbc);

        // 身份证号输入框（自动填充，不可编辑）
        gbc.gridx = 0;
        gbc.gridy = 1;
        formPanel.add(new JLabel("身份证号:"), gbc);
        pidField = new JTextField(20);
        pidField.setText(userPID);
        pidField.setEditable(false);
        pidField.setPreferredSize(new Dimension(250, 30));
        gbc.gridx = 1;
        formPanel.add(pidField, gbc);

        // 存款类型下拉框
        gbc.gridx = 0;
        gbc.gridy = 2;
        formPanel.add(new JLabel("存款类型:"), gbc);
        depositTypeCombo = new JComboBox<>(new String[]{"活期", "定期", "零存整取"});
        depositTypeCombo.setPreferredSize(new Dimension(250, 30));
        gbc.gridx = 1;
        formPanel.add(depositTypeCombo, gbc);

        // 货币类型下拉框
        gbc.gridx = 0;
        gbc.gridy = 3;
        formPanel.add(new JLabel("货币类型:"), gbc);
        curIDCombo = new JComboBox<>(new String[]{"人民币", "美元", "欧元"});
        curIDCombo.setPreferredSize(new Dimension(250, 30));
        gbc.gridx = 1;
        formPanel.add(curIDCombo, gbc);

        // 开卡金额输入框
        gbc.gridx = 0;
        gbc.gridy = 4;
        formPanel.add(new JLabel("开卡金额:"), gbc);
        openMoneyField = new JTextField(20);
        openMoneyField.setPreferredSize(new Dimension(250, 30));
        gbc.gridx = 1;
        formPanel.add(openMoneyField, gbc);

        // 开卡日期标签（自动生成当前日期）
        gbc.gridx = 0;
        gbc.gridy = 5;
        formPanel.add(new JLabel("开卡日期:"), gbc);
        openDateLabel = new JLabel(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        openDateLabel.setBorder(BorderFactory.createLineBorder(Color.GRAY));
        openDateLabel.setPreferredSize(new Dimension(250, 30));
        openDateLabel.setOpaque(true);
        openDateLabel.setBackground(Color.WHITE);
        gbc.gridx = 1;
        formPanel.add(openDateLabel, gbc);

        // 消息标签
        gbc.gridx = 0;
        gbc.gridy = 6;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        messageLabel = new JLabel("", JLabel.CENTER);
        formPanel.add(messageLabel, gbc);

        add(formPanel, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 20));
        JButton registerButton = new JButton("注册银行卡");
        registerButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        registerButton.setPreferredSize(new Dimension(150, 35));
        registerButton.addActionListener(this::registerCard);
        buttonPanel.add(registerButton);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void registerCard(ActionEvent e) {
        String password = new String(passwordField.getPassword());
        String pid = pidField.getText();
        String depositType = (String) depositTypeCombo.getSelectedItem();
        String curID = (String) curIDCombo.getSelectedItem();
        String openDate = openDateLabel.getText();
        String openMoneyText = openMoneyField.getText();

        try {
            // 验证输入
            if (ValidationUtils.isNullOrEmpty(password) ||
                    ValidationUtils.isNullOrEmpty(depositType) ||
                    ValidationUtils.isNullOrEmpty(curID) ||
                    ValidationUtils.isNullOrEmpty(openMoneyText)) {
                showMessage("请填写所有必填字段", Color.RED);
                return;
            }

            // 验证身份证号与当前用户一致（虽然不可编辑，但仍需验证）
            if (!pid.equals(userPID)) {
                showMessage("身份证号必须与当前登录用户一致", Color.RED);
                return;
            }

            // 验证密码格式
            if (!ValidationUtils.validatePassword(password)) {
                showMessage("密码必须为6位数字", Color.RED);
                return;
            }

            // 验证开卡金额
            double openMoney = Double.parseDouble(openMoneyText);
            if (!ValidationUtils.validateAmount(openMoney)) {
                showMessage("开卡金额必须大于0且最多两位小数", Color.RED);
                return;
            }

            // 映射存款类型到savingID
            int savingID = mapDepositTypeToSavingID(depositType);

            // 映射货币类型
            String currency = mapCurrencyType(curID);

            // 执行注册
            cardDAO.createNewCardForUser(
                    Integer.parseInt(customerId),
                    savingID,
                    password,
                    openMoney
            );

            showMessage("银行卡注册成功！", Color.GREEN);

            // 清空输入字段
            passwordField.setText("");
            openMoneyField.setText("");

        } catch (NumberFormatException ex) {
            showMessage("请输入有效的金额数字", Color.RED);
        } catch (SQLException ex) {
            ex.printStackTrace();
            showMessage("操作失败：" + ex.getMessage(), Color.RED);
        } catch (Exception ex) {
            ex.printStackTrace();
            showMessage("操作失败：" + ex.getMessage(), Color.RED);
        }
    }

    private int mapDepositTypeToSavingID(String depositType) {
        switch (depositType) {
            case "活期":
                return 1;
            case "定期":
                return 2;  // 定期一年
            case "零存整取":
                return 6;  // 零存整取一年
            default:
                return 1;  // 默认活期
        }
    }

    private String mapCurrencyType(String curID) {
        switch (curID) {
            case "人民币":
                return "RMB";
            case "美元":
                return "USD";
            case "欧元":
                return "EUR";
            default:
                return "RMB";
        }
    }

    private void showMessage(String text, Color color) {
        messageLabel.setText(text);
        messageLabel.setForeground(color);
    }
}